package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppStore;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.dto.AppStoreDTO;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.AppStoreParam;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppStoreMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppStoreService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppStoreCreateValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppStoreSearchValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppStoreUpdateValidate;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppStoreDetailVo;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppStoreListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 门店实现类
 * @author LikeAdmin
 */
@Service
public class TAppStoreServiceImpl implements ITAppStoreService {
        
    @Resource
    TAppStoreMapper tAppStoreMapper;

    /**
     * 门店列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<TAppStoreListedVo>
     */
    @Override
    public PageResult<TAppStoreListedVo> list(PageValidate pageValidate, TAppStoreSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<TAppStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        tAppStoreMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:name:str",
            "=:pic:str",
            "like:storeFullName@store_full_name:str",
            "=:longitude:long",
            "=:latitude:long",
            "=: businessStartTime@ business_start_time:str",
            "=: businessEndTime@ business_end_time:str",
            "=:phone:str",
            "=:provinceId@province_id:int",
            "=:cityId@city_id:int",
            "=:areaId@area_id:int",
            "=:address:str",
            "=:showAddress@show_address:str",
        });

        IPage<TAppStore> iPage = tAppStoreMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<TAppStoreListedVo> list = new LinkedList<>();
        for(TAppStore item : iPage.getRecords()) {
            TAppStoreListedVo vo = new TAppStoreListedVo();
            BeanUtils.copyProperties(item, vo);
//            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
//            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime().getTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime().getTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 门店详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return TAppStore
     */
    @Override
    public TAppStoreDetailVo detail(Integer id) {
        TAppStore model = tAppStoreMapper.selectOne(
                new QueryWrapper<TAppStore>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TAppStoreDetailVo vo = new TAppStoreDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 门店新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(TAppStoreCreateValidate createValidate) {
        TAppStore model = new TAppStore();
        model.setName(createValidate.getName());
        model.setPic(createValidate.getPic());
        model.setStoreFullName(createValidate.getStoreFullName());
        model.setPhone(createValidate.getPhone());
        model.setAddress(createValidate.getAddress());
        model.setShowAddress(createValidate.getShowAddress());
//        model.setCreateTime(System.currentTimeMillis() / 1000);
//        model.setUpdateTime(System.currentTimeMillis() / 1000);
        tAppStoreMapper.insert(model);
    }

    /**
     * 门店编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(TAppStoreUpdateValidate updateValidate) {
        TAppStore model = tAppStoreMapper.selectOne(
                new QueryWrapper<TAppStore>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setName(updateValidate.getName());
        model.setPic(updateValidate.getPic());
        model.setStoreFullName(updateValidate.getStoreFullName());
        model.setPhone(updateValidate.getPhone());
        model.setAddress(updateValidate.getAddress());
        model.setShowAddress(updateValidate.getShowAddress());
        model.setUpdateTime(new Date());
        tAppStoreMapper.updateById(model);
    }

    /**
     * 门店删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        TAppStore model = tAppStoreMapper.selectOne(
                new QueryWrapper<TAppStore>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        tAppStoreMapper.delete(new QueryWrapper<TAppStore>().eq("id", id));
    }

    /**
     * 门店查询
     * @param param
     * @return
     */
    @Override
    public List<TAppStore> selectList(AppStoreParam param) {
        String name = param.getName();
        Integer amount = param.getAmount();
        String provinceCode =param.getProvinceCode();
        String cityCode = param.getCityCode();
        String areaCode = param.getAreaCode();

        Integer dicId = param.getDicId();
        String dicType = param.getDicType();
        QueryWrapper<TAppStore> wrapper = new QueryWrapper<>();
        if(name != null && !name.isEmpty()) {
            wrapper.like("store_full_name", "%"+name+"%");
        }
        if(provinceCode!=null && !provinceCode.isEmpty()){
            wrapper.eq("province_code", provinceCode);
        }
        if(cityCode!=null && !cityCode.isEmpty()){
            wrapper.eq("city_code", cityCode);
        }
        if(areaCode!=null && !areaCode.isEmpty()){
            wrapper.eq("area_code", areaCode);
        }
        if(dicId != null && dicType != null && !dicType.isEmpty()) {
            wrapper.eq("dic_id", dicId);
            wrapper.eq("dic_type", dicType);
        }
        List<TAppStore> appStoreList = Optional.ofNullable(tAppStoreMapper.selectList(wrapper)).orElse(new ArrayList<>());
        if(amount!=null && amount>0 && appStoreList.size()>amount){
            return appStoreList.subList(0, amount);
        }
        return appStoreList;
    }

    @Override
    public List<AppStoreDTO> selectDtoList(AppStoreParam param) {
        String name = param.getName();
        Integer amount = param.getAmount();
        Integer cityId = param.getCityId();
        Integer dicId = param.getDicId();
        String dicType = param.getDicType();
        QueryWrapper<TAppStore> wrapper = new QueryWrapper<>();
        if(name != null && !name.isEmpty()) {
            wrapper.like("store_full_name", "%"+name+"%");
        }
        if(cityId != null) {
            wrapper.eq("city_id", cityId);
        }
        if(dicId != null && dicType != null && !dicType.isEmpty()) {
            wrapper.eq("dic_id", dicId);
            wrapper.eq("dic_type", dicType);
        }
        List<TAppStore> appStoreList = Optional.ofNullable(tAppStoreMapper.selectList(wrapper)).orElse(new ArrayList<>());
        List<AppStoreDTO> collect = appStoreList.stream().map(item -> {
            AppStoreDTO dto = new AppStoreDTO();
            BeanUtils.copyProperties(item, dto);
            dto.setBusinessStartTime(TimeUtils.dateToTimeToString(item.getBusinessStartTime(), "HH:mm:ss"));
            dto.setBusinessEndTime(TimeUtils.dateToTimeToString(item.getBusinessEndTime(), "HH:mm:ss"));
            Boolean checkNow = TimeUtils.checkNow(item.getBusinessStartTime(), item.getBusinessEndTime());
            dto.setStatus(checkNow?"营业中":"休息中");
            return dto;
        }).collect(Collectors.toList());
        if(amount!=null && amount>0 && collect.size()>amount){
            return collect.subList(0, amount);
        }
        return collect;
    }

}
